/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: UserController
 * Author:   石贵武
 * Date:     2018\3\6 0006 16:49
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhoudongxiu.dto.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 石贵武
 * @create 2018\3\6 0006
 * @since 1.0.0
 */
@RestController
@Slf4j
public class UserController {

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @JsonView(User.UserSimplView.class)
    @ApiOperation(value = "查询服务")
    public List<User> query() {

        return Arrays.asList(new User(), new User(), new User());
    }

    @GetMapping("/user/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@ApiParam(value = "用户id") @PathVariable String id) {
        User user = new User();
        user.setUsername("shiguiwu");
        return user;
    }

    @PostMapping("/user")
    public User create(@Valid @RequestBody User user) {
        User use = user;
        return use;
    }

    @PutMapping("/user")
    public User update(@Valid @RequestBody User user, BindingResult result) {
        if (result.hasErrors()) {
            result.getAllErrors().stream().forEach(e -> log.error("校验错误={}", e.getDefaultMessage()));
        }

        User use = user;
        use.setUsername("周冬修");
        use.setBrithday(new Date());
        return use;
    }

    @DeleteMapping("user/{id}")
    public void delete(@PathVariable String id) {
        log.info("要删除的id：id={}", id);
    }

    @GetMapping("/me")
    public Object getCurrentUser(Authentication user, HttpServletRequest request) {

        String header = request.getHeader("Authencation");
        String token = StringUtils.substringAfter(header, "bearer ");
        try {
            Claims claims = Jwts.parser().setSigningKey("shiguiwu".getBytes("UTF-8")).parseClaimsJws(token).getBody();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return user;
    }
}